package com.teamwings.api.controller;


import cn.hutool.core.io.LineHandler;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.teamwings.common.constant.CommonConstant;
import com.teamwings.common.vo.Result;
import com.teamwings.ctrls.FormComponent;
import com.teamwings.modules.code.entity.FormTableCode;
import com.teamwings.modules.code.service.IFormTableCodeService;
import com.teamwings.modules.design.vo.FormVo;
import com.teamwings.modules.head.entity.FormTableHead;
import com.teamwings.modules.head.service.IFormTableHeadService;
import com.teamwings.util.VoUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.form.api.vo.FormInfoDetailVO;
import org.jeecg.common.form.api.vo.FormModelVO;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@Api("表单服务对外api")
@RequestMapping("/form/api")
public class ApiController {

    @Autowired
    private IFormTableHeadService headService;

    @Autowired
    private IFormTableCodeService codeService;

    @Autowired
    private ISysBaseAPI iSysBaseAPI;

    /**
     * 获取表单控件
     * @param formHeadId
     * @return
     */
    public JSONArray getFormCtrlList(String formHeadId, FormTableHead head){
        if (head == null) {
            head = headService.getById(formHeadId);
        }
        FormTableCode formTableCode = codeService.getByFormIdAndVersion(head.getId(), head.getTableVersion());

        if (formTableCode == null) {
            // return Result.error("未找到对应的控件");
            return null;
        }

        JSONObject obj = JSON.parseObject(formTableCode.getTableCode());
        // 获取code中的控件
        JSONArray jsonList = obj.getJSONArray("list");
        return jsonList;
    }

    /**
     * 列表查询
     */
    @ApiOperation(value = "获取表单及其所属控件详细信息", notes = "获取表单及其所属控件详细信息")
    @GetMapping(value = "/formInfoDetails/{formId}")
    public Result<?> getFormInfoDetail(@PathVariable(value = "formId") String formHeadId) {
        FormTableHead head = headService.getById(formHeadId);
        JSONArray jsonList = this.getFormCtrlList(formHeadId, head);

        if (jsonList == null) {
            return Result.error("未找到对应的控件");
        }

        Function<String, JSONArray> fn = (headId) -> this.getFormCtrlList(headId, null);

        //递归遍历出控件
        FormInfoDetailVO detailVo = codeService.getComponentForRecursion(jsonList, new FormInfoDetailVO(), fn);

        detailVo.setFormId(head.getId())
            .setFormName(head.getTableCname())
            .setFormDesc(head.getTableTxt());

        return Result.OK(detailVo);
    }


    /**
     * 获取指定流程图的表单信息
     */
    @ApiOperation(value = "获取指定流程图的表单信息", notes = "获取指定流程图的表单信息")
    @GetMapping(value = "/formModels/{mapId}")
    public Result<?> getFormModelList(@PathVariable String mapId) {

        List<String> tableIds = iSysBaseAPI.getTableIdByFlowId(mapId);

        if (tableIds == null || tableIds.size() == 0) {
            return Result.error("没有找到对应的表单");
        }

//        List<String> tableCodes = codeService.getTableCodeWithHeads(new LambdaQueryWrapper<FormTableCode>()
//            .in(FormTableCode::getTableHeadId, tableIds));

        LambdaQueryWrapper<FormTableCode> queryWrapper = new LambdaQueryWrapper<FormTableCode>().in(FormTableCode::getTableHeadId, tableIds);
        queryWrapper.in(FormTableCode::getTableHeadId, tableIds);
        queryWrapper.select(FormTableCode::getTableCode);
        List<FormTableCode> list = codeService.list(queryWrapper);

        if (list.size() == 0) {
            return Result.error("找到了表单设计头id，没有与其对应的form_table_code数据");
        }

        List<String> tableCodes = list.stream().map(FormTableCode::getTableCode).collect(Collectors.toList());

        List<FormModelVO> vos = tableCodes.stream().map(item -> {
            FormVo formVo = VoUtils.newFormVo(item);
            FormModelVO formModelVo = new FormModelVO();
            formModelVo.setFormId(formVo.getTableHeadId())
                .setTableName(formVo.getTableCname())
                .setTableType(formVo.getTableName())
                .setItems(formVo.getList().stream().map(FormComponent::getKey).collect(Collectors.toList()));
            //添加通用字段
            formModelVo.getItems().addAll(CommonConstant.COMMON_TABLE_COLUMN);
            return formModelVo;
        }).collect(Collectors.toList());

        return Result.OK(vos);
    }



}
